<template>
	<view class="container">
		<!-- 记录列表 -->
		<view class="record-list">
			<view v-if="records.length === 0" class="empty-tip">暂无记录</view>
			<view v-else>
				<view v-for="(record, index) in records" :key="index" class="record-item">
					<view class="record-left">
						<view class="record-type">
							<text>{{record.type}}</text>
						</view>
						<view class="record-info">
							<text class="record-date">{{record.date}}</text>
							<text v-if="record.note" class="record-note">{{record.note}}</text>
							<view v-if="record.images && record.images.length" class="record-images">
								<image v-for="(img, idx) in record.images" :key="idx" :src="img.url || img" class="record-thumb" mode="aspectFill" />
							</view>
						</view>
					</view>
					<view class="record-right">
						<text :class="['record-amount', record.amount > 0 ? 'income' : 'expense']">
							{{record.amount > 0 ? '+' : ''}}¥{{record.amount}}
						</text>
						<view class="record-actions">
							<uni-icons type="compose" size="20" color="#666" @click="editRecord(index)" />
							<uni-icons type="trash" size="20" color="#666" @click="deleteRecord(index)" />
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加记录按钮 -->
		<view class="add-button" @click="showAddModal">
			<uni-icons type="plusempty" size="30" color="#FFF"/>
		</view>

		<!-- 添加/编辑记录弹窗 -->
		<uni-popup ref="popup" type="dialog">
			<view class="popup-content">
				<view class="popup-scroll">
					<view class="popup-title">{{isEdit ? '编辑记录' : '添加记录'}}</view>
					<view class="form-item">
						<view class="form-label">类型</view>
						<uni-segmented-control 
							:current="formData.recordType === '收入' ? 0 : 1"
							:values="['收入', '支出']"
							@clickItem="onTypeChange"
						/>
					</view>
					<view class="form-item">
						<view class="form-label">分类</view>
						<picker 
							:range="currentCategories" 
							range-key="name"
							:value="categoryIndex"
							@change="onCategoryChange"
						>
							<view class="picker">
								<text v-if="formData.type">{{formData.type}}</text>
								<text v-else class="placeholder">请选择分类</text>
								<uni-icons type="bottom" size="14" color="#666"/>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<view class="form-label">金额</view>
						<uni-easyinput
							v-model="formData.amount"
							type="number"
							placeholder="请输入金额"
						/>
					</view>
					<view class="form-item">
						<view class="form-label">日期</view>
						<uni-datetime-picker
							v-model="formData.date"
							type="date"
						/>
					</view>
					<view class="form-item">
						<view class="form-label">备注</view>
						<uni-easyinput
							v-model="formData.note"
							placeholder="可填写备注信息"
						/>
					</view>
					<view class="form-item">
						<view class="form-label">图片（可选，最多9张）</view>
						<uni-file-picker
							v-model="formData.images"
							limit="9"
							file-mediatype="image"
							mode="grid"
							@select="onImagesSelect"
						/>
					</view>
				</view>
				<view class="form-buttons">
					<button class="btn cancel" @click="closePopup">取消</button>
					<button class="btn confirm" @click="saveRecord">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			records: [],
			isEdit: false,
			editIndex: -1,
			formData: {
				recordType: '支出',
				type: '',
				amount: '',
				date: new Date().toISOString().split('T')[0],
				note: '',
				images: []
			},
			incomeCategories: [],
			expenseCategories: [],
			categoryIndex: 0
		}
	},
	computed: {
		currentCategories() {
			return this.formData.recordType === '收入' ? this.incomeCategories : this.expenseCategories
		}
	},
	onShow() {
		this.loadCategories()
		this.loadFromStorage()
	},
	methods: {
		loadCategories() {
			const incomeCategories = uni.getStorageSync('incomeCategories') || []
			const expenseCategories = uni.getStorageSync('expenseCategories') || []
			this.incomeCategories = incomeCategories
			this.expenseCategories = expenseCategories
		},
		loadFromStorage() {
			const records = uni.getStorageSync('records') || []
			this.records = records
		},
		saveToStorage() {
			uni.setStorageSync('records', this.records)
		},
		showAddModal() {
			this.isEdit = false
			this.editIndex = -1
			this.formData = {
				recordType: '支出',
				type: '',
				amount: '',
				date: new Date().toISOString().split('T')[0],
				note: '',
				images: []
			}
			this.categoryIndex = 0
			this.$refs.popup.open()
		},
		editRecord(index) {
			this.isEdit = true
			this.editIndex = index
			const record = this.records[index]
			this.formData = {
				recordType: record.amount > 0 ? '收入' : '支出',
				type: record.type,
				amount: Math.abs(record.amount).toString(),
				date: record.date,
				note: record.note || '',
				images: (record.images || []).map(url => ({url}))
			}
			const categories = record.amount > 0 ? this.incomeCategories : this.expenseCategories
			this.categoryIndex = categories.findIndex(c => c.name === record.type)
			if (this.categoryIndex === -1) this.categoryIndex = 0
			this.$refs.popup.open()
		},
		deleteRecord(index) {
			uni.showModal({
				title: '提示',
				content: '确定要删除这条记录吗？',
				success: (res) => {
					if (res.confirm) {
						this.records.splice(index, 1)
						this.saveToStorage()
						this.loadFromStorage()
					}
				}
			})
		},
		onTypeChange(e) {
			this.formData.recordType = e.currentIndex === 0 ? '收入' : '支出'
			this.formData.type = ''
			this.categoryIndex = 0
		},
		onCategoryChange(e) {
			this.categoryIndex = e.detail.value
			this.formData.type = this.currentCategories[this.categoryIndex]?.name || ''
		},
		closePopup() {
			this.$refs.popup.close()
		},
		saveRecord() {
			if (!this.formData.type || !this.formData.amount) {
				uni.showToast({
					title: '请填写完整信息',
					icon: 'none'
				})
				return
			}
			const record = {
				type: this.formData.type,
				amount: Number(this.formData.amount) * (this.formData.recordType === '收入' ? 1 : -1),
				date: this.formData.date,
				note: this.formData.note,
				images: this.formData.images.map(f => f.url)
			}
			console.log('即将保存的记录:', record)
			if (this.isEdit) {
				this.records[this.editIndex] = record
			} else {
				this.records.unshift(record)
			}
			this.saveToStorage()
			this.loadFromStorage()
			this.closePopup()
			uni.showToast({
				title: this.isEdit ? '修改成功' : '添加成功'
			})
		},
		onImagesSelect(e) {
			const newFiles = (e.tempFilePaths || []).map(url => ({ url }));
			const all = [...this.formData.images, ...newFiles];
			const unique = [];
			const urlSet = new Set();
			for (const f of all) {
				if (!urlSet.has(f.url)) {
					urlSet.add(f.url);
					unique.push(f);
				}
			}
			this.formData.images = unique;
			console.log('追加后formData.images:', this.formData.images);
		}
	}
}
</script>

<style>
.container {
	padding: 20rpx;
	padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
}

.record-list {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.record-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #eee;
}

.record-item:last-child {
	border-bottom: none;
}

.record-left {
	display: flex;
	flex-direction: column;
}

.record-type {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.record-info {
	font-size: 24rpx;
	color: #999;
	display: flex;
	flex-direction: column;
}

.record-note {
	font-size: 24rpx;
	color: #888;
	margin-top: 4rpx;
	word-break: break-all;
}

.record-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	flex-shrink: 0;
}

.record-amount {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.income {
	color: #4cd964;
}

.expense {
	color: #ff3b30;
}

.record-actions {
	display: flex;
	gap: 20rpx;
}

.add-button {
	position: fixed;
	right: 40rpx;
	bottom: calc(140rpx + env(safe-area-inset-bottom));
	width: 100rpx;
	height: 100rpx;
	background-color: #007aff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.2);
	z-index: 100;
}

.popup-content {
	background-color: #fff;
	border-radius: 20rpx;
	width: 600rpx;
	box-sizing: border-box;
	max-height: 80vh;
	display: flex;
	flex-direction: column;
	padding: 0;
}

.popup-scroll {
	flex: 1 1 auto;
	padding: 30rpx 30rpx 0 30rpx;
	overflow-y: auto;
	min-height: 0;
}

.popup-title {
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 30rpx;
}

.form-item {
	margin-bottom: 30rpx;
}

.form-label {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.picker {
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 10rpx;
	padding: 0 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.placeholder {
	color: #999;
}

.form-buttons {
	display: flex;
	gap: 20rpx;
	padding: 20rpx 30rpx 30rpx 30rpx;
	background: #fff;
	border-bottom-left-radius: 20rpx;
	border-bottom-right-radius: 20rpx;
	box-shadow: 0 -4rpx 16rpx rgba(0,0,0,0.06);
	position: sticky;
	bottom: 0;
	z-index: 10;
}

.btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 40rpx;
	font-size: 28rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
}

.cancel {
	background-color: #f5f5f5;
	color: #666;
}

.confirm {
	background-color: #007aff;
	color: #fff;
}

.empty-tip {
	color: #999;
	text-align: center;
	padding: 40rpx 0;
}

.record-images {
	display: flex;
	gap: 10rpx;
	margin-top: 6rpx;
	overflow-x: auto;
	max-width: 70vw;
}

.record-thumb {
	width: 60rpx;
	height: 60rpx;
	border-radius: 8rpx;
	object-fit: cover;
	border: 1rpx solid #eee;
	flex-shrink: 0;
}
</style> 